<?php
class LoginCtl extends BaseCtl {
	public function LoginCtl(){
		parent::BaseCtl();
	}
	
	public function login(){
		try {
			$form = $this->getLoginForm();
			
			$lg = $form->getLogin();
			$pass = $form->getPassword();
			
			// login must be provided
			if($this->isEmpty($lg)){
				throw new Exception('Login is mandatory, please provide a value');
			}
			else {
				// then get the user and check first the 
				// regular password, then the readonly password
				
				$service = new Service();
				$usr = $service->getUserByLogin($lg);
				
				if($usr == null){
					throw new Exception('Invalid credentials');
				}
				else {
					$checked = false; 
					$readonly = false; 
					
					if($this->checkPassword($pass, $usr->getPass())){
						$checked = true;
						$readonly = false;  
					}
					else if($this->checkPassword($pass, $usr->getPassRo())){
						$checked = true;
						$readonly = true;
					}
					
					if(! $checked){
						throw new Exception('Invalid credentials');
					}
					else {
						$sess = HtmlUtil::getSessionUser(); 
						
						$sess->setReadonly($readonly);
						$sess->setUser($usr);
						
						$this->redirect('albums.php');
					}
				}
			}
		}
		catch(Exception $e){
			HtmlUtil::addError($e->getMessage());
		}
	}
	
    public function isPostback(){
    	return 'login' == $this->getPost('pagename');
    }

    public function loadData(){
    	$form = $this->getLoginForm();
    	
    	$form->setLogin($this->getPost('login'));
    	$form->setPassword($this->getPost('password'));
    }
} 
?>
